<template>
	<view class="result-container">
		<!-- 导航栏 -->
		<u-navbar title="支付结果" :border-bottom="false" :background="{ backgroundColor: '#fff' }">
			<template #left>
				<u-icon name="close" size="20" @click="goHome"></u-icon>
			</template>
		</u-navbar>
		
		<!-- 支付结果 -->
		<view class="result-content">
			<!-- 成功状态 -->
			<view v-if="paymentStatus === 'success'" class="result-success">
				<view class="success-icon">
					<u-icon name="checkmark-circle-fill" color="#52c41a" size="80"></u-icon>
				</view>
				<text class="result-title">支付成功</text>
				<text class="result-desc">您的订单已支付成功，我们将尽快为您处理</text>
			</view>
			
			<!-- 失败状态 -->
			<view v-else-if="paymentStatus === 'failed'" class="result-failed">
				<view class="failed-icon">
					<u-icon name="close-circle-fill" color="#ff4d4f" size="80"></u-icon>
				</view>
				<text class="result-title">支付失败</text>
				<text class="result-desc">{{ failedReason || '支付过程中出现问题，请重试' }}</text>
			</view>
			
			<!-- 处理中状态 -->
			<view v-else class="result-pending">
				<view class="pending-icon">
					<u-icon name="clock" color="#faad14" size="80"></u-icon>
				</view>
				<text class="result-title">支付处理中</text>
				<text class="result-desc">正在确认您的支付信息，请稍候...</text>
			</view>
		</view>
		
		<!-- 订单信息 -->
		<view class="order-info" v-if="orderInfo">
			<view class="info-item">
				<text class="info-label">订单号</text>
				<text class="info-value">{{ orderInfo.order_no }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">支付金额</text>
				<text class="info-value amount">¥{{ orderInfo.total_amount }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">支付时间</text>
				<text class="info-value">{{ formatTime(orderInfo.pay_time) }}</text>
			</view>
			<view class="info-item" v-if="orderInfo.payment_method">
				<text class="info-label">支付方式</text>
				<text class="info-value">{{ getPaymentMethodName(orderInfo.payment_method) }}</text>
			</view>
		</view>
		
		<!-- 温馨提示 -->
		<view class="tips-section" v-if="paymentStatus === 'success'">
			<view class="tips-header">
				<u-icon name="info-circle" color="#1890ff" size="18"></u-icon>
				<text class="tips-title">温馨提示</text>
			</view>
			<view class="tips-list">
				<text class="tip-item">• 您可以在"我的订单"中查看订单详情</text>
				<text class="tip-item">• 如有问题请及时联系客服</text>
				<text class="tip-item">• 感谢您的信任与支持</text>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button v-if="paymentStatus === 'success'" class="btn btn-outline" @click="viewOrder">
				查看订单
			</button>
			<button v-if="paymentStatus === 'failed'" class="btn btn-outline" @click="retryPayment">
				重新支付
			</button>
			<button v-if="paymentStatus === 'pending'" class="btn btn-outline" @click="checkPaymentStatus">
				刷新状态
			</button>
			<button class="btn btn-primary" @click="continueShopping">
				继续购物
			</button>
		</view>
		
		<!-- 客服联系 -->
		<view class="contact-service" @click="contactService">
			<u-icon name="headphones" color="#666" size="20"></u-icon>
			<text class="contact-text">联系客服</text>
		</view>
	</view>
</template>

<script>
import api from '@/api/index.js'

export default {
	data() {
		return {
			orderId: '',
			paymentStatus: 'pending', // success, failed, pending
			failedReason: '',
			orderInfo: null,
			checkTimer: null
		}
	},
	
	onLoad(options) {
		this.orderId = options.order_id || ''
		this.paymentStatus = options.status || 'pending'
		this.failedReason = options.reason || ''
		
		this.loadOrderInfo()
		
		// 如果是处理中状态，定时检查支付状态
		if (this.paymentStatus === 'pending') {
			this.startStatusCheck()
		}
	},
	
	onUnload() {
		// 清除定时器
		if (this.checkTimer) {
			clearInterval(this.checkTimer)
		}
	},
	
	methods: {
		// 返回首页
		goHome() {
			uni.switchTab({
				url: '/pages/index/index'
			})
		},
		
		// 加载订单信息
		async loadOrderInfo() {
			if (!this.orderId) return
			
			try {
				const res = await api.orderApi.getOrderDetail(this.orderId)
				if (res.r === 0) {
					this.orderInfo = res.data
					
					// 根据订单状态更新支付状态
					if (res.data.pay_status === 1) {
						this.paymentStatus = 'success'
					} else if (res.data.pay_status === -1) {
						this.paymentStatus = 'failed'
					}
				}
			} catch (error) {
				console.error('加载订单信息失败:', error)
			}
		},
		
		// 开始状态检查
		startStatusCheck() {
			let checkCount = 0
			const maxChecks = 30 // 最多检查30次（5分钟）
			
			this.checkTimer = setInterval(async () => {
				checkCount++
				
				await this.loadOrderInfo()
				
				// 如果状态已确定或达到最大检查次数，停止检查
				if (this.paymentStatus !== 'pending' || checkCount >= maxChecks) {
					clearInterval(this.checkTimer)
					this.checkTimer = null
					
					// 如果超时仍未确定状态，设为失败
					if (checkCount >= maxChecks && this.paymentStatus === 'pending') {
						this.paymentStatus = 'failed'
						this.failedReason = '支付超时，请重试'
					}
				}
			}, 10000) // 每10秒检查一次
		},
		
		// 手动检查支付状态
		async checkPaymentStatus() {
			uni.showLoading({ title: '检查中...' })
			
			try {
				await this.loadOrderInfo()
				
				if (this.paymentStatus === 'pending') {
					uni.showToast({
						title: '支付仍在处理中',
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: '状态已更新',
						icon: 'success'
					})
				}
			} catch (error) {
				uni.showToast({
					title: '检查失败，请重试',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 查看订单
		viewOrder() {
			uni.navigateTo({
				url: `/pages/order/detail?id=${this.orderId}`
			})
		},
		
		// 重新支付
		retryPayment() {
			uni.navigateTo({
				url: `/pages/payment/index?order_id=${this.orderId}&total=${this.orderInfo?.total_amount || '0.00'}`
			})
		},
		
		// 继续购物
		continueShopping() {
			uni.switchTab({
				url: '/pages/index/index'
			})
		},
		
		// 联系客服
		contactService() {
			uni.showActionSheet({
				itemList: ['在线客服', '客服电话'],
				success: (res) => {
					if (res.tapIndex === 0) {
						// 跳转到客服页面
						uni.navigateTo({
							url: '/pages/service/chat'
						})
					} else if (res.tapIndex === 1) {
						// 拨打客服电话
						uni.makePhoneCall({
							phoneNumber: '400-123-4567'
						})
					}
				}
			})
		},
		
		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return '-'
			
			const date = new Date(timestamp * 1000)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			
			return `${year}-${month}-${day} ${hours}:${minutes}`
		},
		
		// 获取支付方式名称
		getPaymentMethodName(method) {
			const methods = {
				wechat: '微信支付',
				alipay: '支付宝',
				balance: '余额支付'
			}
			return methods[method] || method
		}
	}
}
</script>

<style scoped>
.result-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 40rpx;
}

/* 支付结果 */
.result-content {
	background-color: #fff;
	padding: 80rpx 30rpx 60rpx;
	text-align: center;
	margin-bottom: 20rpx;
}

.result-success,
.result-failed,
.result-pending {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 20rpx;
}

.success-icon,
.failed-icon,
.pending-icon {
	margin-bottom: 10rpx;
}

.result-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.result-desc {
	font-size: 28rpx;
	color: #666;
	line-height: 1.5;
	max-width: 500rpx;
}

/* 订单信息 */
.order-info {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 2rpx solid #f0f0f0;
}

.info-item:last-child {
	border-bottom: none;
}

.info-label {
	font-size: 28rpx;
	color: #666;
}

.info-value {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.info-value.amount {
	color: #ff4d4f;
	font-weight: bold;
}

/* 温馨提示 */
.tips-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.tips-header {
	display: flex;
	align-items: center;
	gap: 10rpx;
	margin-bottom: 20rpx;
}

.tips-title {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.tips-list {
	gap: 10rpx;
}

.tip-item {
	font-size: 24rpx;
	color: #666;
	line-height: 1.5;
	margin-bottom: 8rpx;
	display: block;
}

/* 操作按钮 */
.action-buttons {
	padding: 0 30rpx;
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-bottom: 40rpx;
}

.btn {
	height: 88rpx;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.btn-primary {
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: #fff;
}

.btn-outline {
	background-color: #fff;
	color: #667eea;
	border: 2rpx solid #667eea;
}

/* 客服联系 */
.contact-service {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
	padding: 30rpx;
}

.contact-text {
	font-size: 28rpx;
	color: #666;
}
</style>